import { createApp } from 'vue'
import App from './App.vue'
import naive from 'naive-ui'
import router from './myroute'
import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate'
import './utils/fix-userid-types' // 导入userId类型修复脚本
import './styles/index.scss' // 导入统一样式系统
import { webSocketService } from './modules/shared/services/websocket-service'

// 添加更详细的错误处理
window.addEventListener('error', (event) => {
  console.error('全局错误捕获:', {
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno,
    error: event.error?.stack || event.error
  })
  
  // 尝试将错误信息写入到文件或发送到服务器
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[ERROR] ${event.message} at ${event.filename}:${event.lineno}:${event.colno}`)
  }
})

window.addEventListener('unhandledrejection', (event) => {
  console.error('未处理的Promise拒绝:', event.reason)
  
  // 尝试将错误信息写入到文件或发送到服务器
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[UNHANDLED_REJECTION] ${event.reason}`)
  }
})

// 添加资源加载错误监听
window.addEventListener('error', (event) => {
  if (event.target !== window) {
    const target = event.target as any;
    console.error('资源加载失败:', {
      element: target.tagName,
      source: target.src || target.href,
      error: event.message
    })
    
    if (window.electronAPI?.writeLog) {
      window.electronAPI.writeLog(`[RESOURCE_ERROR] Failed to load ${target.tagName}: ${target.src || target.href}`)
    }
  }
}, true)

// 添加控制台日志重定向，以便在Electron中查看
const originalConsole = {
  log: console.log,
  error: console.error,
  warn: console.warn,
  info: console.info
}

console.log = function(...args) {
  originalConsole.log.apply(console, args)
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[LOG] ${args.join(' ')}`)
  }
}

console.error = function(...args) {
  originalConsole.error.apply(console, args)
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[ERROR] ${args.join(' ')}`)
  }
}

console.warn = function(...args) {
  originalConsole.warn.apply(console, args)
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[WARN] ${args.join(' ')}`)
  }
}

console.info = function(...args) {
  originalConsole.info.apply(console, args)
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[INFO] ${args.join(' ')}`)
  }
}

const app = createApp(App)
const pinia = createPinia()
// 配置持久化插件
pinia.use(createPersistedState({
  // 默认使用localStorage
  storage: localStorage,
  // 序列化函数
  serializer: {
    serialize: JSON.stringify,
    deserialize: JSON.parse,
  }
}))

app.use(naive)
app.use(router)
app.use(pinia)

// 添加应用级别的错误处理
app.config.errorHandler = (err: any, _instance, info) => {
  console.error('Vue应用错误:', err, info)
  
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[VUE_ERROR] ${err?.message || err} - ${info}`)
  }
}

// 添加性能监控
const startTime = performance.now()
window.addEventListener('load', () => {
  const loadTime = performance.now() - startTime
  console.log(`应用加载时间: ${loadTime}ms`)
  
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[PERFORMANCE] App loaded in ${loadTime}ms`)
  }
})

// 添加路由变化监听
window.addEventListener('popstate', () => {
  console.log('路由变化:', window.location.pathname)
  
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog(`[ROUTE] Changed to ${window.location.pathname}`)
  }
})

// 添加DOM加载完成监听
document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM加载完成')
  
  if (window.electronAPI?.writeLog) {
    window.electronAPI.writeLog('[DOM] DOMContentLoaded')
  }
})

// 添加应用初始化日志
console.log('开始初始化应用...')

// 在应用卸载时清理WebSocket连接
window.addEventListener('unload', () => {
  webSocketService.cleanup()
})

// 添加应用初始化日志
console.log('Starting Vue application initialization...');

try {
  // 将app实例挂载到window对象上，以便其他组件可以访问
  if (typeof window !== 'undefined') {
    (window as any).vueApp = app;
  }
  
  app.mount('#app');
  console.log('Vue application mounted successfully');
} catch (error) {
  console.error('Failed to mount Vue application:', error);
}
